export class Delay {
  constructor() {
    this.timerId = null;
    this.remainingTime = 0;
    this.startTime = 0;
    this.isPaused = false;
    this.deferred = null;
  }

  start(ms) {
    this.startTime = Date.now();
    this.remainingTime = ms;
    this.isPaused = false;

    this.deferred = new Promise((resolve) => {
      this.timerId = setTimeout(() => {
        resolve();
        this.timerId = null;
      }, this.remainingTime);
    });

    return this.deferred;
  }

  pause() {
    if (!this.isPaused && this.timerId && this.deferred) {
      clearTimeout(this.timerId);
      this.remainingTime -= Date.now() - this.startTime;
      this.isPaused = true;
    }
  }

  resume() {
    if (this.isPaused && this.deferred) {
      this.isPaused = false;
      this.startTime = Date.now();

      this.deferred = new Promise((resolve) => {
        this.timerId = setTimeout(() => {
          resolve();
          this.timerId = null;
        }, this.remainingTime);
      });

      return this.deferred;
    }
  }

  clear() {
    if (this.timerId && this.deferred) {
      clearTimeout(this.timerId);
      this.timerId = null;
      this.remainingTime = 0;
      this.isPaused = false;
      this.deferred = null;
    }
  }
}
